<?php
/**
 * Created by PhpStorm.
 * User: LYQ
 * Date: 2020/1/11
 * Time: 13:18
 */

namespace app\index\controller;


class EasyRefund extends Base
{
    public $APPID = 'wx9ff56a4c00b4e96d';
    public $MCH_ID = '1456031502';
    public $API_KEY = 'a1b2c3d4e5f6g7123456789101112131';
    public function easyRefund($totalFee,$refundFee,$refundNo,$wxOrderNo,$orderNo,$refundDesc)
    {
//        * @param float $totalFee 订单金额 单位元
//        * @param float $refundFee 退款金额 单位元
//        * @param string $refundNo 退款单号
//        * @param string $wxOrderNo 微信订单号 (商户订单号与微信订单号二选一，至少填一个)
//        * @param string $orderNo 商户订单号 (商户订单号与微信订单号二选一，至少填一个)
//        * @param string $refundDesc 退款原因
        $info = $this->doRefund(
//            1,
//            1,
//            '2020011012074116309',
//            '4200000485202001107176829556',
//            '2020011012074116309',
//            '无'
            $totalFee,$refundFee,$refundNo,$wxOrderNo,$orderNo,$refundDesc
        );
        if($info['status'] == 1){
            $this->apiReturn(200,'退款成功');
        }else{
            $this->apiReturn(303,'退款失败');
        }
    }




    /**
     * 退款
     * @param float $totalFee 订单金额 单位元
     * @param float $refundFee 退款金额 单位元
     * @param string $refundNo 退款单号
     * @param string $wxOrderNo 微信订单号 (商户订单号与微信订单号二选一，至少填一个)
     * @param string $orderNo 商户订单号 (商户订单号与微信订单号二选一，至少填一个)
     * @param string $refundDesc 退款原因
     * @return string
     */
    public function doRefund($totalFee, $refundFee, $refundNo, $wxOrderNo='',$orderNo='', $refundDesc='') {
        //所需数据
        $data = [
            'appid' => $this->APPID, //公众号appId
            'mch_id' => $this->MCH_ID, //商户号id
            'nonce_str' => $this->createNonceStr(), //生成随机字符串
            'total_fee' => intval($totalFee * 100), //订单金额  单位 转为分
            'refund_fee' => intval($refundFee * 100), //退款金额 单位 转为分
            'sign_type' => 'MD5', //签名类型 支持HMAC-SHA256和MD5，默认为MD5
            'transaction_id' => $wxOrderNo, //微信订单号
            'out_trade_no' => $orderNo, //商户订单号
            'out_refund_no' => $refundNo, //商户退款单号
            'refund_desc' => $refundDesc, //退款原因（选填）
        ];

        //生成签， $this->API_KEY 商户号API秘钥
        $data['sign'] = $this->getRefundSign($data, $this->API_KEY);
        //发送xml数据
        $responseXml = $this->curlPost('https://api.mch.weixin.qq.com/secapi/pay/refund', self::arrayToXml($data));

        $unifiedOrder = simplexml_load_string($responseXml, 'SimpleXMLElement', LIBXML_NOCDATA);

        if($unifiedOrder === false) {
            //写日志查看错误
            //payLogAdd('微信订单号：'.$wxOrderNo.'，微信退款xml解析错误');
        }
        if($unifiedOrder->return_code != 'SUCCESS') {
            $error = ['info'=>'微信订单号：'.$wxOrderNo,'error'=>$unifiedOrder->return_msg,'status'=>0];
            //写日志查看错误
            //payLogAdd(json_encode($error,JSON_UNESCAPED_UNICODE));
        }
        if($unifiedOrder->result_code != 'SUCCESS') {
            $error = ['info'=>'微信订单号：'.$wxOrderNo,'error'=>$unifiedOrder->err_code_des,'status'=>0];

            //写日志查看错误
            //payLogAdd(json_encode($error,JSON_UNESCAPED_UNICODE));
        }
        if(empty($error)) $error = ['info'=>'退款成功','status'=>1];
        return $error;
    }
    /*
     * 组成微信需要XML数据
     */
    public static function arrayToXml($arr) {
        $xml = "<xml>";
        foreach ($arr as $key => $val) {
            if (is_numeric($val)) {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            } else {
                $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
            }
        }
        $xml .= "</xml>";
        return $xml;
    }
    /*
     * 生成随机字符串方法
     */
    protected function createNonceStr($length = 32){
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ( $i = 0; $i < $length; $i++ ) {
            $str .= substr($chars, mt_rand(0, strlen($chars)-1), 1);
        }
        return $str;
    }
    /*
     * 生成退款使用签名
     */
    protected static function getRefundSign($params, $key) {
        ksort($params, SORT_STRING);
        $unSignParaString = self::formatQueryParaMap($params, false);
        $signStr = strtoupper(md5($unSignParaString . "&key=" . $key));

        return $signStr;
    }
    /*
     * 将退款需要的信息组成签名算法
     */
    protected static function formatQueryParaMap($paraMap, $urlEncode = false) {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v) {
            if (null != $v && "null" != $v) {
                if ($urlEncode) {
                    $v = urlencode($v);
                }
                $buff .= $k . "=" . $v . "&";
            }
        }
        $reqPar = '';
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff) - 1);
        }

        return $reqPar;
    }
    /*
     * 微信退款使用curl方法
     */
    protected function curlPost($url = '', $postData = '', $options = array()) {
        if (is_array($postData)) {
            $postData = http_build_query($postData);
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置cURL允许执行的最长秒数
        if (!empty($options)) {
            curl_setopt_array($ch, $options);
        }
        //https请求 不验证证书和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        //第一种方法，cert 与 key 分别属于两个.pem文件
        //默认格式为PEM，可以注释
        curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');
        curl_setopt($ch, CURLOPT_SSLCERT, ROOT_PATH .'vendor'.DS.'wxpay'.DS.'cert'.DS.'apiclient_cert.pem'); //证书绝对路径
        //默认格式为PEM，可以注释
        curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');
        curl_setopt($ch, CURLOPT_SSLKEY, ROOT_PATH .'vendor'.DS.'wxpay'.DS.'cert'.DS.'apiclient_key.pem');//证书绝对路径
        //第二种方式，两个文件合成一个.pem文件
        //curl_setopt($ch,CURLOPT_SSLCERT,getcwd().'/all.pem');
        $data = curl_exec($ch);
        if ($data) {
            curl_close($ch);
            return $data;
        } else {
            $error = curl_errno($ch);
            echo "curl出错，错误码: ".$error."<br>";
            curl_close($ch);
            return false;
        }
    }
}